package com.qiaotongtianxia.loans.net;

import android.content.Context;
import android.support.annotation.Nullable;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qiaotongtianxia.loans.bean.BaseBack;
import com.qiaotongtianxia.loans.bean.Recommender;
import com.qiaotongtianxia.loans.bean.Member;
import com.qiaotongtianxia.loans.bean.Refund;
import com.qiaotongtianxia.loans.bean.RefundBean;
import com.qiaotongtianxia.loans.beanManager.MemberManager;
import com.qiaotongtianxia.loans.functionInterface.IBaseRequestImp;
import com.qiaotongtianxia.loans.util.CommonUtils;
import com.qiaotongtianxia.loans.util.ConstansUrls;
import com.qiaotongtianxia.loans.util.SPUtil;
import com.qiaotongtianxia.loans.util.ToastUtil;
import com.qiaotongtianxia.loans.views.BaseProgress;
import com.qiaotongtianxia.loans.views.LoadingProgress;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by lisen on 2017/12/13.
 *
 * @author lisen < 4533548588@qq.com >
 */

@SuppressWarnings("all")
public class Api{

    private BaseProgress progress;
    private Context context;
    private Request request;
    private Gson gson ;
    private TreeMap<String, Object> map;
    private String token;
    private Member member ;

    public Api(Context context) {
        this.context = context;
        progress = new LoadingProgress(context);
        gson = new Gson();
        token = SPUtil.getString(context,SPUtil.APPTOKEN,SPUtil.APPTOKEN_KEY,"无token");
        map = new TreeMap<>();
        request = new Request(this,new RequestViewImp());
        request.setToken(token);
        member = MemberManager.getMember(context);
    }

    /**
     * 设置自己想要的等待框，null 不显示等待框
     * @param progressBar
     */
    public void setDefaultProgress(@Nullable BaseProgress progressBar){
        progress = progressBar;
    }

    /**
     * 在request开始请求时，最先开始执行此处代码,
     *
     * 同时开始多次请求时 onStartProgress-onEnd 只会执行一次
     * onStart每次请求都会执行，
     */
    private class RequestViewImp implements IRequestView{
        @Override
        public void onStartProgress() {
            if (progress != null){
                progress.show();
            }
        }
        @Override
        public boolean onStart() {
            if (!CommonUtils.isNetworkConnected(context)){
                return false;
            }
            return true;
        }
        @Override
        public void onEnd() {
            LogUtils.i("Actiivty : ----> "+context.getClass().getSimpleName());
            if (progress != null){
                progress.dismiss();
            }
        }
    }

    /**
     * 防止内存泄露
     * 原因（在网络请求的过程中Activity就关闭了，
     *          Presenter（Api）还持有了V层的引用，也就是MainActivity，就会内存泄露）
     */
    public void detach(){
        context = null;
    }

    @Nullable
    public BaseProgress getProgress(){
        return progress;
    }

    private <T> List<T> checkList(List<T> list) {
        return list == null ? new ArrayList<T>() : list;
    }
    /**
     * 获取token
     * @param iBaseRequestImp
     */
    public void token(final IBaseRequestImp<String> iBaseRequestImp){
        iBaseRequestImp.onRequest();
        request.sendPost(ConstansUrls.TOKEN, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                try {
                    JSONObject jsonObject = new JSONObject(baseBack.getData());
                    SPUtil.save(context, SPUtil.APPTOKEN,SPUtil.APPTOKEN_KEY,jsonObject.optString("token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }

            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     *  注册
     * @param account
     * @param password
     * @param iBaseRequestImp
     */
    public void registe(String account,String password,String password2,String nickName,String sms,String tuijianren,
                             final IBaseRequestImp<String> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",account);
        map.put("password",password);
        map.put("password2",password2);
        map.put("nickname",nickName);
        map.put("sms",sms);
        map.put("tuijianren",tuijianren);
        request.sendPost(ConstansUrls.REGISTER, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess("注册成功！");
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 登录
     * @param account
     * @param password
     * @param iBaseRequestImp
     */
    public void login(final String account, String password, final IBaseRequestImp<Nullable> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",account);
        map.put("password",password);
        request.sendPost(ConstansUrls.LOGIN, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                try {
                    JSONObject jsonObject = new JSONObject(baseBack.getData());
                    SPUtil.save(context,SPUtil.MEMBER,SPUtil.MEMBER_KEY,jsonObject.optString("member"));
                    SPUtil.save(context,SPUtil.ACCOUNTS,account,account);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                iBaseRequestImp.onRequestSuccess( null);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 待还款列表
     * @param iBaseRequestImp
     */
    public void waitRefund(final IBaseRequestImp<List<Refund>> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.WAIT_REFUND, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                List<Refund> refunds = gson.fromJson(baseBack.getData(),new TypeToken<List<Refund>>(){}.getType());
                iBaseRequestImp.onRequestSuccess(checkList(refunds));
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * certificate
     * @param iBaseRequestImp
     */
    public void isCertificate(final IBaseRequestImp<Map<String,String>> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.IS_CERTIFICATE, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                Map<String,String> result = gson.fromJson(baseBack.getData(),new TypeToken<Map<String,String>>(){}.getType());
                iBaseRequestImp.onRequestSuccess(result == null ? new HashMap<String, String>() : result);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 上传图片
     * @param image
     * @param iBaseRequestImp
     */
    public void uploadImg(File image, final IBaseRequestImp<String> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("image",image);
        request.upload(ConstansUrls.UPLOADIMG, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                String url = "";
                try {
                    JSONObject jsonObject = new JSONObject(baseBack.getData());
                    url = jsonObject.optString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                iBaseRequestImp.onRequestSuccess(url);
            }

            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 实名认证
     * @param map
     * @param iBaseRequestImp
     */
    public void certificate(TreeMap<String,Object> map, final IBaseRequestImp<Nullable>iBaseRequestImp){
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.CERTIFICATE, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(null);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 上传通讯录
     * @param tel_str
     * @param iBaseRequestImp
     */
    public void upLoadContacts(String tel_str, final IBaseRequestImp<Nullable> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("tel_str",tel_str);
        request.sendPost(ConstansUrls.UPLOAD_CONTACTS, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(null);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 退出登录
     * @param iBaseRequestImp
     */
    public void logout(final IBaseRequestImp<Nullable> iBaseRequestImp){
        request.sendPost(ConstansUrls.LOGOUT, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(null);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 还款
     * @param iBaseRequestImp
     */
    public void refund(String id,String orderId,String amount,String orderImg,final IBaseRequestImp<String> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("id",id);
        map.put("orderId",orderId);
        map.put("amount",amount);
        map.put("orderImg",orderImg);
        request.sendPost(ConstansUrls.REFUND, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

//   request.downLoad(ConstansUrls.QRCODE, context.getFilesDir()+Constants.APP_FILE_DIR, "qr.jpg", iBaseRequestImp);
    /**
     * 下载图片
     * @param iBaseRequestImp
     */
    public void QRCode(final IBaseRequestImp<String> iBaseRequestImp){
        request.sendPost(ConstansUrls.QRCODE, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(ConstansUrls.HOST + baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 贷款
     * @param map
     * @param iBaseRequestImp
     */
    public void loans(TreeMap<String,Object> map,final IBaseRequestImp<String> iBaseRequestImp){
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.LOANS, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }
    /**
     * 贷款记录
     * @param map
     * @param iBaseRequestImp
     */
    public void loansRecord(int type,final IBaseRequestImp<List<Refund>> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        map.put("type",type);
        request.sendPost(ConstansUrls.LOANS_RECORD, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                List<Refund> refunds = gson.fromJson(baseBack.getData(),new TypeToken<List<Refund>>(){}.getType());
                iBaseRequestImp.onRequestSuccess(checkList(refunds));
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }
    /**
     * 还款记录
     * @param map
     * @param iBaseRequestImp
     */
    public void refundRecord(int type,final IBaseRequestImp<List<RefundBean>> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        map.put("type",type);
        request.sendPost(ConstansUrls.REFUND_RECORD, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                List<RefundBean> refundBeanList = gson.fromJson(baseBack.getData(),new TypeToken<List<RefundBean>>(){}.getType());
                iBaseRequestImp.onRequestSuccess(checkList(refundBeanList));
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }
    /**
     * 还款提示
     * @param map
     * @param iBaseRequestImp
     */
    public void refundTip(final IBaseRequestImp<String> iBaseRequestImp){
        request.sendPost(ConstansUrls.REFUND_TIP, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }
    /**
     * 贷款提示
     * @param map
     * @param iBaseRequestImp
     */
    public void loansTip(final IBaseRequestImp<String> iBaseRequestImp){
        request.sendPost(ConstansUrls.LOANS_TIP, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }
    /**
     * 客服信息
     * @param map
     * @param iBaseRequestImp
     */
    public void service(final IBaseRequestImp<Map<String,String>> iBaseRequestImp){
        request.sendPost(ConstansUrls.SERVICE, null, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                Map<String,String> result = gson.fromJson(baseBack.getData(),new TypeToken<Map<String,String>>(){}.getType());
                iBaseRequestImp.onRequestSuccess(result);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     *获取短信验证码
     * @param iBaseRequestImp
     */
    public void verifyCode(String mobile,final IBaseRequestImp<String> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("mobile",mobile);
        request.sendPost(ConstansUrls.PHONE_CODE, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 忘记密码
     * @param mobile
     * @param iBaseRequestImp
     */
    public void forgetPW(String account,String newpwd1,String newpwd2,String sms,final IBaseRequestImp<Nullable> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",account);
        map.put("newpwd1",newpwd1);
        map.put("newpwd2",newpwd2);
        map.put("sms",sms);
        request.sendPost(ConstansUrls.FORGETPW, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(null);
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     *
        判断是否是老客户
     */
    public void isRegular(final IBaseRequestImp<Boolean> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.IS_REGULAR, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                try {
                    JSONObject jsonObject = new JSONObject(baseBack.getData());
                    String is_familiar_guest = jsonObject.optString("is_familiar_guest");
                    if ("1".equals(is_familiar_guest)){
                        iBaseRequestImp.onRequestSuccess(true);
                    }else{
                        iBaseRequestImp.onRequestSuccess(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    iBaseRequestImp.onRequestSuccess(false);
                }
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 直接借款
     * @param amount
     * @param iBaseRequestImp
     */
    public void directLoans(String amount,final IBaseRequestImp<String> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        map.put("amount",amount);
        request.sendPost(ConstansUrls.DIRECT_LOANS, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                iBaseRequestImp.onRequestSuccess(baseBack.getData());
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

    /**
     * 所有下级用户第一笔借款状态
     * @param iBaseRequestImp
     */
    public void recommends(final IBaseRequestImp<List<Recommender>> iBaseRequestImp){
        map = new TreeMap<>();
        map.put("account",member.getAccount());
        request.sendPost(ConstansUrls.RECOMMENDERS, map, new ARequstCall() {
            @Override
            public void onSuccessCall(BaseBack baseBack) {
                List<Recommender> list = null;
                try {
                    JSONObject jsonObject = new JSONObject(baseBack.getData());
                    String json = jsonObject.optString("loan_list");
                    list = gson.fromJson(json,new TypeToken<List<Recommender>>(){}.getType());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                iBaseRequestImp.onRequestSuccess(checkList(list));
            }
            @Override
            public void onFailedCall(int errorCode, String errorMsg) {
                ToastUtil.showShort(context,errorMsg);
                iBaseRequestImp.onRequestError(errorCode,errorMsg);
            }
        });
    }

}
